package com.wzw.shoppingcart.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzw.shoppingcart.entity.Product;
import com.wzw.shoppingcart.service.ProductService;
import com.wzw.shoppingcart.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 *@author wzw
 * 2023/4/7
 */
@RestController
@RequestMapping("/product")
@RequiredArgsConstructor
public class ProductController {
    private final ProductService productService;

    @GetMapping("/list")
    public Result<Page<Product>> getProducts(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            String keyword) {
        QueryWrapper<Product> queryWrapper = Wrappers.query();
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like("product_name", keyword);
        }
        Page<Product> productPage = productService.page(new Page<>(pageNum, pageSize),queryWrapper);
        return Result.success(productPage);
    }

    @GetMapping("/id")
    public Product getProductById(@RequestParam("id") Integer id) {
        return productService.getById(id);
    }

    @PostMapping
    public boolean saveProduct(@RequestBody Product product) {
        return productService.save(product);
    }

    @DeleteMapping
    public boolean deleteProductByIds(@RequestBody Integer[] ids) {

        return productService.removeBatchByIds(Arrays.asList(ids));
    }
    @PutMapping
    public boolean updateProduct(@RequestBody Product product) {

        UpdateWrapper<Product> wrapper = new UpdateWrapper<>();
        wrapper.eq("product_id", product.getProductId());
        return productService.update(product, wrapper);
    }



}
